package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.BaseBean
import com.two.screen.water.balance.bean.CollectMoneyBean
import com.two.screen.water.balance.bean.MyTextWatcher
import com.two.screen.water.balance.bean.database.OrderDB
import com.two.screen.water.balance.bean.database.ServerOrderResult
import com.two.screen.water.balance.bean.database.ServerVipInfo
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.net.api.NormalApi
import com.two.screen.water.balance.net.api.OrderApi
import com.two.screen.water.balance.net.api.OrderApi.ORDER_TYPE_NORMAL
import com.two.screen.water.balance.net.api.OrderApi.PAY_TYPE_CASH
import com.two.screen.water.balance.net.api.OrderApi.PAY_TYPE_JUHE
import com.two.screen.water.balance.net.api.OrderApi.PAY_TYPE_SCAN_QR
import com.two.screen.water.balance.net.api.OrderApi.PAY_TYPE_VIP_CARD
import com.two.screen.water.balance.net.api.OrderApi.PAY_TYPE_WETCH_VIP
import com.two.screen.water.balance.net.observer.DialogObserver
import com.two.screen.water.balance.net.observer.NormalObserver
import com.two.screen.water.balance.print.PrinterAll
import com.two.screen.water.balance.print.bean.PrintOrderBean
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import com.two.screen.water.balance.utils.eventbus.EventCode
import com.two.screen.water.balance.widget.dialog.WaitingPayDialog
import com.two.screen.water.balance.widget.keyboard.collect_money.KeyboardUtilCollectMoney
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_collect_money.*
import me.grantland.widget.AutofitTextView
import java.util.concurrent.TimeUnit

@Route(path = ARouterUtils.CollectMoneyActivity)
class CollectMoneyActivity : BaseActivity() {
    override fun getContentLayout(): Any = R.layout.activity_collect_money


    private var mKeyboardUtilCollectMoney: KeyboardUtilCollectMoney? = null

    @JvmField @Autowired var mDataJson: String? = null
    private var mCollectMoneyBean: CollectMoneyBean? = null

    private var mCurPayType = 0 //0现金   1会员码    2聚合支付 3 会员卡
    private var mIsRealPriceFocus = true

    //    var mCancelPayDialog: AlertDialog? = null
    var mWaitingPayDialog: WaitingPayDialog? = null

    private var orderDB: OrderDB? = null
    private var mIsConfirmClick = false
    override fun beforeSetContentView() {
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
        super.beforeSetContentView()
    }

    override fun initView(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        mKeyboardUtilCollectMoney = KeyboardUtilCollectMoney(this@CollectMoneyActivity, false)
        initPayAtv()
        initPayBtn()
    }

    private var mPayBtnListAtv: MutableList<AutofitTextView> = mutableListOf()

    @SuppressLint("CheckResult")
    private fun initPayAtv() {
        var inflater = LayoutInflater.from(this)
        DataApi.mPayButtonList.forEach {
            val avt = inflater.inflate(R.layout.activity_collect_money_pay_tv, mPayLayout, false) as AutofitTextView
            avt.text = it.title
            //1现金支付，2会员码支付，3会员卡支付，4聚合码支付，5扫码收款
            mPayBtnListAtv.add(avt)
            avt.setOnClickListener { v -> updatePayUi(OrderApi.getLocalPayType(it.pay_id), avt) }
            mPayLayout.addView(avt)
        }
        //默认第一个
        val atv = mPayBtnListAtv.firstOrNull()
        val payButton = DataApi.mPayButtonList.firstOrNull()
        if (atv != null && payButton != null) {
            updatePayUi(OrderApi.getLocalPayType(payButton.pay_id), atv)
        }
    }


    private fun initPayBtn() {
        //mVipPayAtv.visibility = if (DataApi.mIsConnectNet) View.VISIBLE else View.GONE
        //mVipCardPayAtv.visibility = if (DataApi.mIsConnectNet) View.VISIBLE else View.GONE
        //mJuHePayAtv.visibility = if (DataApi.mIsConnectNet) View.VISIBLE else View.GONE
        //mScanQrPayAtv.visibility = if (DataApi.mIsConnectNet) View.VISIBLE else View.GONE
        //if (DataApi.mReaderIndex == 0) mVipCardPayAtv.visibility = View.GONE
    }

    private var isAutoConnectPrint = false

    private var mGetPayResultEmitter: ObservableEmitter<String>? = null
    private var mPollingGetPayResultDisposable: Disposable? = null
    private var mPollingGetPayResultDisposable1: Disposable? = null

    override fun initData() {
        d("mDataJson:$mDataJson")
        mCollectMoneyBean = try {
            CommUtils.gson.fromJson(mDataJson, CollectMoneyBean::class.java)
        } catch (e: Exception) {
            null
        }
        mTotalPriceEt.setText(mCollectMoneyBean?.totalPrice ?: "0.00")
        mDiscountPercentEt.setText(mCollectMoneyBean?.pendingOrder?.discountPercent?.toString() ?: "100")//TODO:创建好数据库，使用那边赋值
        //mRealIncomeEt.setText(mCollectMoneyBean?.totalPrice ?: "0.00")//这里还需要计算一下实际收款
        calcRealIncome()
        calcFindZero()
        isAutoConnectPrint = SPUtils.getBoolean(Params.isAutoPayPrint, true)
        initChooseIv()
    }

    private fun initChooseIv() {
        mPrintTicketIv.setImageResource(if (isAutoConnectPrint) R.drawable.svg_choose_selected else R.drawable.svg_choose_unselected)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initListener() {
        mPrintTicketLayout.setOnClickListener {
            isAutoConnectPrint = !isAutoConnectPrint
            SPUtils.putBoolean(Params.isAutoPayPrint, isAutoConnectPrint)
            initChooseIv()
        }

        mGoBackLayout.setOnClickListener { goBack() }
//        mTotalPriceEt.setOnTouchListener { v: View?, event: MotionEvent ->
//            if (event.action == MotionEvent.ACTION_UP) {
//                mKeyboardUtilCollectMoney?.attachTo(mTotalPriceEt)
//            }
//            false
//        }
        mDiscountPercentEt.setOnTouchListener { v: View?, event: MotionEvent ->
            if (event.action == MotionEvent.ACTION_UP) {
                mKeyboardUtilCollectMoney?.attachTo(mDiscountPercentEt)
            }
            false
        }
        mRealIncomeEt.setOnTouchListener { v: View?, event: MotionEvent ->
            if (event.action == MotionEvent.ACTION_UP) {
                mKeyboardUtilCollectMoney?.attachTo(mRealIncomeEt)
            }
            false
        }
        mRealIncomeEt?.isEnabled = true //默认实收选中
        mRealIncomeEt?.requestFocus()
        mKeyboardUtilCollectMoney?.attachTo(mRealIncomeEt)
//        updatePayUi(PAY_TYPE_JUHE, avt)
//        mCashPayAtv.setOnClickListener { updatePayUi(PAY_TYPE_CASH) }
//        mVipPayAtv.setOnClickListener { updatePayUi(PAY_TYPE_WETCH_VIP) }
//        mVipCardPayAtv.setOnClickListener { updatePayUi(PAY_TYPE_VIP_CARD) }
//        mJuHePayAtv.setOnClickListener { updatePayUi(PAY_TYPE_JUHE) }
//        mScanQrPayAtv.setOnClickListener { updatePayUi(PAY_TYPE_SCAN_QR) }

        //修改总价，影响找零
//        mTotalPriceEt.addTextChangedListener(object : MyTextWatcher() {
//            override fun afterTextChanged(s: Editable) {
//                calcRealIncome()
//            }
//        })
        mDiscountPercentEt.addTextChangedListener(object : MyTextWatcher() {
            override fun afterTextChanged(s: Editable) {
                //处理>=100
                CommUtils.println("DiscountPercent->", s.toString())
                var discountPercent = try {
                    mDiscountPercentEt?.text?.toString()?.toInt() ?: 100
                } catch (e: Exception) {
                    100
                }
                if (discountPercent > 100) {
                    mDiscountPercentEt?.setText("100")
                    mDiscountPercentEt?.selectAll()
                }
                calcRealIncome()
            }
        })
        //修改实收，影响找零
        mRealIncomeEt.addTextChangedListener(object : MyTextWatcher() {
            override fun afterTextChanged(s: Editable) {
                calcFindZero()
            }
        })

        //判断实收 是否拥有焦点
        mRealIncomeEt.setOnFocusChangeListener { v, hasFocus ->
            d("判断实收 是否拥有焦点：$hasFocus")
            mIsRealPriceFocus = hasFocus
        }

        //键盘  “确认回调”
        mKeyboardUtilCollectMoney?.setOnKeyboardUtilCollectMoneyListener {
            d("mIsRealPriceFocus:$mIsRealPriceFocus,mIsConfirmClick:$mIsConfirmClick")
            if (mIsRealPriceFocus) {
                if (mIsConfirmClick) {
                    ToastUtil.showToast("操作太快了，稍后再试!")
                    return@setOnKeyboardUtilCollectMoneyListener
                }
                mIsConfirmClick = true
                d("mCurPayType$mCurPayType;mIsConfirmClick:$mIsConfirmClick")
                if (PAY_TYPE_CASH != mCurPayType) {
                    //这里处理现金支付，其他支付方式，来个2秒拦截。
                    mRealIncomeEt.postDelayed({ mIsConfirmClick = false }, 2000)
                }

                val totalPrice = try {
                    mTotalPriceEt.text.toString().toDouble()
                } catch (e: Exception) {
                    0.0
                }
                //TODO:这里还需要写入字段
                val discountPercent = try {
                    mDiscountPercentEt.text.toString().toInt()
                } catch (e: Exception) {
                    100
                }
                val realPrice = try {
                    mRealIncomeEt.text.toString().toDouble()
                } catch (e: Exception) {
                    0.0
                }
                val findZero = try {
                    mFindZeroTv.text.toString().toDouble()
                } catch (e: Exception) {
                    0.00
                }
                // 直接收银
                if (orderDB == null) {
                    orderDB = OrderApi.createOrderDB(findZero, discountPercent, totalPrice, realPrice, mCurPayType, mPayTypeNameTv.text.toString(), ORDER_TYPE_NORMAL)
                    orderDB!!.orderStatus = OrderApi.ORDER_STATUS_PAYING
                    OrderApi.saveOrderDB(orderDB!!, mCollectMoneyBean?.goodsList)
                } else {
                    //存在订单就去更改，不重新生成
                    orderDB!!.orderStatus = OrderApi.ORDER_STATUS_PAYING
                    OrderApi.updateOrderDB(orderDB!!, findZero, discountPercent, totalPrice, realPrice, mCurPayType, mPayTypeNameTv.text.toString(), ORDER_TYPE_NORMAL)
                }

                if (DataApi.mIsConnectNet) {
                    //现金支付
                    d("orderDB!!.payType:${orderDB!!.payType}")
                    when (orderDB!!.payType) {
                        // 0现金   1微会员    2聚合支付
                        PAY_TYPE_CASH.toString() -> {
                            //直接上传，传完改支付状态，上传状态
                            var sob = OrderApi.toServerOrderBean(orderDB!!)
                            //由于现金积分支付，默认是已经支付的。
                            orderDB!!.orderStatus = OrderApi.ORDER_STATUS_PAID
                            App.mDaoSession?.orderDBDao?.update(orderDB)
                            NormalApi.postPay(
                                sortedMapOf(
                                    Params.pay_t to sob.pay_t, Params.price to sob.price, Params.data to CommUtils.gson.toJson(sob.data),
                                    Params.d_price to orderDB?.giftPrice, Params.gd_price to orderDB?.totalGiftPrice, Params.diff_price to orderDB?.findZero,
                                    Params.d_c to String.format("%.2f", (orderDB?.discountPercent ?: 0) / 100.0),
                                    Params.od_n to sob.od_n, Params.c_time to sob.c_time, Params.wg to sob.wg
                                ), Urls.pay
                            )
                                .compose(RxUtils.aLifecycle(this))
                                .compose(RxUtils.io())
                                .subscribe(object : DialogObserver<ServerOrderResult>(this) {
                                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                                        var data = t.data!!
                                        //把订单状态改成已支付。
                                        orderDB!!.uploadStatus = 1
                                        orderDB!!.orderStatus = OrderApi.ORDER_STATUS_PAID
                                        //这里应该还需要保存 积分二维码.
                                        orderDB!!.integralUrl = data.integral_url
                                        App.mDaoSession?.orderDBDao?.update(orderDB)
                                        //是否打印？
                                        if (isAutoConnectPrint) PrinterAll.printOrder(PrintOrderBean.orderDB2PrintOrderBean(orderDB))
                                        EventBusUtil.sendEvent(Event(EventCode.COLLECT_MONEY_SUCCESS))
                                        //如果是挂单的话，恢复原先状态。
                                        removePendingOrder()
                                        goBack()
                                    }

                                    override fun onError(e: Throwable) {
                                        mIsConfirmClick = false
                                        super.onError(e)
                                    }
                                })
                        }
                        PAY_TYPE_WETCH_VIP.toString() -> {
                            var sob = OrderApi.toServerOrderBean(orderDB!!)
                            NormalApi.postPay(
                                sortedMapOf(
                                    Params.pay_t to sob.pay_t, Params.price to sob.price, Params.data to CommUtils.gson.toJson(sob.data),
                                    Params.d_price to orderDB?.giftPrice, Params.gd_price to orderDB?.totalGiftPrice, Params.diff_price to orderDB?.findZero,
                                    Params.d_c to String.format("%.2f", (orderDB?.discountPercent ?: 0) / 100.0),
                                    Params.od_n to sob.od_n, Params.c_time to sob.c_time, Params.wg to sob.wg
                                ), Urls.pay
                            )
                                .compose(RxUtils.aLifecycle(this))
                                .compose(RxUtils.io())
                                .subscribe(object : DialogObserver<ServerOrderResult>(this) {
                                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                                        val data = t.data!!
                                        orderDB!!.uploadStatus = 1
                                        App.mDaoSession?.orderDBDao?.update(orderDB)
                                        data.orderDB = orderDB
                                        //显示收款二维码,进行轮询支付结果。
                                        pollingRequestPayResult(data)
                                        EventBusUtil.sendEvent(Event(EventCode.ORDER_ON_PAY_VIP, data))
                                        //弹出等待框
                                        if (mWaitingPayDialog == null) mWaitingPayDialog = WaitingPayDialog(this@CollectMoneyActivity)
                                        mWaitingPayDialog?.show()
                                        mWaitingPayDialog?.setShowData(WaitingPayDialog.PAY_TYPE_VIP, data, String.format("%.2f", realPrice), mPayTypeNameTv.text.toString())
                                        mWaitingPayDialog?.setWaitingPayDialogListener(object : WaitingPayDialog.WaitingPayDialogListener() {
                                            override fun dismiss() {
                                                //取消支付，应该需要把订单改成取消支付状态。
                                                //orderDB.orderStatus = 5
                                                // App.mDaoSession?.orderDBDao?.update(orderDB)
                                                EventBusUtil.sendEvent(Event(EventCode.ORDER_CANCEL))
                                                mWaitingPayDialog?.dismiss()
                                            }
                                        })
                                    }
                                })
                        }
                        PAY_TYPE_VIP_CARD.toString() -> {
                            if (mWaitingPayDialog == null) mWaitingPayDialog = WaitingPayDialog(this@CollectMoneyActivity)
                            mWaitingPayDialog?.show()
                            mWaitingPayDialog?.setShowData(WaitingPayDialog.PAY_TYPE_SHUA_KA, null, String.format("%.2f", realPrice), mPayTypeNameTv.text.toString())
                            mWaitingPayDialog?.setWaitingPayDialogListener(object : WaitingPayDialog.WaitingPayDialogListener() {
                                override fun dismiss() {
                                    EventBusUtil.sendEvent(Event(EventCode.ORDER_CANCEL))
                                    mWaitingPayDialog?.dismiss()
                                }
                            })
                        }
                        PAY_TYPE_JUHE.toString() -> {
                            var sob = OrderApi.toServerOrderBean(orderDB!!)
                            NormalApi.postPay(
                                sortedMapOf(
                                    Params.pay_t to sob.pay_t, Params.price to sob.price, Params.data to CommUtils.gson.toJson(sob.data),
                                    Params.d_price to orderDB?.giftPrice, Params.gd_price to orderDB?.totalGiftPrice, Params.diff_price to orderDB?.findZero,
                                    Params.d_c to String.format("%.2f", (orderDB?.discountPercent ?: 0) / 100.0),
                                    Params.od_n to sob.od_n, Params.c_time to sob.c_time, Params.wg to sob.wg
                                ), Urls.pay
                            )
                                .compose(RxUtils.aLifecycle(this))
                                .compose(RxUtils.io())
                                .subscribe(object : DialogObserver<ServerOrderResult>(this) {
                                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                                        orderDB!!.uploadStatus = 1
                                        App.mDaoSession?.orderDBDao?.update(orderDB)
                                        val data = t.data!!
                                        data.orderDB = orderDB
                                        //显示收款二维码,进行轮询支付结果。
                                        pollingRequestPayResult(data)
                                        EventBusUtil.sendEvent(Event(EventCode.ORDER_ON_PAY_JUHE, data))
                                        //弹出等待框
                                        if (mWaitingPayDialog == null) mWaitingPayDialog = WaitingPayDialog(this@CollectMoneyActivity)
                                        mWaitingPayDialog?.show()
                                        mWaitingPayDialog?.setShowData(WaitingPayDialog.PAY_TYPE_JUHE, data, String.format("%.2f", realPrice), mPayTypeNameTv.text.toString())
                                        mWaitingPayDialog?.setWaitingPayDialogListener(object : WaitingPayDialog.WaitingPayDialogListener() {
                                            override fun dismiss() {
                                                EventBusUtil.sendEvent(Event(EventCode.ORDER_CANCEL))
                                                mWaitingPayDialog?.dismiss()
                                            }
                                        })
                                    }
                                })
                        }
                        PAY_TYPE_SCAN_QR.toString() -> {
                            //先弹出等待框获取扫码付款二维码信息，再轮询等待
                            if (mWaitingPayDialog == null) mWaitingPayDialog = WaitingPayDialog(this@CollectMoneyActivity)
                            mWaitingPayDialog?.show()
                            mWaitingPayDialog?.setShowData(WaitingPayDialog.PAY_TYPE_SCAN_QR, null, String.format("%.2f", realPrice), mPayTypeNameTv.text.toString())
                            mWaitingPayDialog?.setWaitingPayDialogListener(object : WaitingPayDialog.WaitingPayDialogListener() {
                                override fun dismiss() {
                                    EventBusUtil.sendEvent(Event(EventCode.ORDER_CANCEL))
                                    mWaitingPayDialog?.dismiss()
                                }

                                override fun getAuthCodeSuccess(code: String) {
                                    d("getAuthCodeSuccess->code:$code,线程：${Thread.currentThread().name}")
                                    var sob = OrderApi.toServerOrderBean(orderDB!!)
                                    NormalApi.postPay(
                                        sortedMapOf(
                                            Params.pay_t to sob.pay_t, Params.price to sob.price, Params.data to CommUtils.gson.toJson(sob.data),
                                            Params.d_price to orderDB?.giftPrice, Params.gd_price to orderDB?.totalGiftPrice, Params.diff_price to orderDB?.findZero,
                                            Params.d_c to String.format("%.2f", (orderDB?.discountPercent ?: 0) / 100.0),
                                            Params.od_n to sob.od_n, Params.c_time to sob.c_time, Params.wg to sob.wg, Params.auth_code to code
                                        ), Urls.pay
                                    )
                                        .compose(RxUtils.aLifecycle(this@CollectMoneyActivity))
                                        .compose(RxUtils.io())
                                        .subscribe(object : DialogObserver<ServerOrderResult>(this@CollectMoneyActivity) {
                                            override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                                                val data = t.data!!
                                                data.orderDB = orderDB
                                                orderDB!!.uploadStatus = 1
                                                App.mDaoSession?.orderDBDao?.update(orderDB)

                                                //显示收款二维码,进行轮询支付结果。
                                                pollingRequestPayResult(data)
                                                EventBusUtil.sendEvent(Event(EventCode.VICE_SCREEN_SHOW_STATICE_PAY, data))
                                            }
                                        })
                                }
                            })
                        }
                    }

                } else {
                    if (orderDB!!.payType == PAY_TYPE_CASH.toString()) {
                        orderDB!!.orderStatus = OrderApi.ORDER_STATUS_PAID
                        App.mDaoSession?.orderDBDao?.update(orderDB)
                        //这里临时发通知说订单完成
                        EventBusUtil.sendEvent(Event(EventCode.COLLECT_MONEY_SUCCESS))
                        //是否打印
                        if (isAutoConnectPrint) PrinterAll.printOrder(PrintOrderBean.orderDB2PrintOrderBean(orderDB))

                        //如果是挂单的话，恢复原先状态。
                        removePendingOrder()
                        //返回
                        goBack()
                    } else {
                        ToastUtil.showToast("请检查网络后重试")
                    }
                }
            } else {
                mIsConfirmClick = false
                mRealIncomeEt?.requestFocus()
                //mTotalPriceEt?.clearFocus()
                mDiscountPercentEt?.clearFocus()
                mRealIncomeEt?.setSelectAllOnFocus(true)
                mRealIncomeEt?.selectAll()
                mKeyboardUtilCollectMoney?.attachTo(mRealIncomeEt)
            }
        }
    }


    private fun cancelPollingGetPayResult() {
        mGetPayResultEmitter?.onNext("")
        mPollingGetPayResultDisposable1?.dispose()
        mPollingGetPayResultDisposable?.dispose()
    }

    //这个轮询支付结果不应该放在此处，因为还需要考虑到单屏情况下。建议放在CollectMoneyActivity
    private fun pollingRequestPayResult(serverOrderResult: ServerOrderResult?) {
        cancelPollingGetPayResult()
        d("pollingRequestPayResult:地址：${serverOrderResult?.qr_url},订单：${serverOrderResult?.od_n}")
        Observable.create(ObservableOnSubscribe<String> { e ->
            mGetPayResultEmitter = e
            NormalApi.postPay(sortedMapOf(Params.od_n to serverOrderResult?.od_n), Urls.orderQuery)
                .compose(RxUtils.aLifecycle(this))
                .subscribe(object : NormalObserver<ServerOrderResult>() {
                    override fun onSubscribe(d: Disposable) {
                        mPollingGetPayResultDisposable1 = d
                    }

                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                        var data = t.data!!
                        //订单状态 0 未支付 1已支付 注：状态0时继续轮询，1代表支付成功
                        if (data.od_status == 1) {
                            //更改已支付，打印。
                            //把订单状态改成已支付。
                            serverOrderResult?.orderDB?.uploadStatus = 1
                            serverOrderResult?.orderDB?.orderStatus = 2
                            serverOrderResult?.orderDB?.integralUrl = serverOrderResult?.integral_url
                            App.mDaoSession?.orderDBDao?.update(serverOrderResult?.orderDB)
                            if (isAutoConnectPrint) PrinterAll.printOrder(PrintOrderBean.orderDB2PrintOrderBean(serverOrderResult?.orderDB))

                            if (mWaitingPayDialog?.isShowing == true) {
                                mWaitingPayDialog?.setPaySuccess()
                                mWaitingPayDialog?.setWaitingPayDialogListener(object : WaitingPayDialog.WaitingPayDialogListener() {
                                    override fun autoClosePay() {
                                        EventBusUtil.sendEvent(Event(EventCode.VICE_SCREEN_SHOW_STATICE_PAY))
                                        cancelPollingGetPayResult()
                                        //支付成功，通知回去。可以通过订单号
                                        EventBusUtil.sendEvent(Event(EventCode.ORDER_PAY_RESULT, serverOrderResult))
                                    }
                                })
                                return
                            }
                            EventBusUtil.sendEvent(Event(EventCode.VICE_SCREEN_SHOW_STATICE_PAY))
                            cancelPollingGetPayResult()
                            //支付成功，通知回去。可以通过订单号
                            EventBusUtil.sendEvent(Event(EventCode.ORDER_PAY_RESULT, serverOrderResult))
                        } else {
                            mGetPayResultEmitter?.onComplete()
                        }
                    }

                    override fun dataIsNull(t: BaseBean<out ServerOrderResult>) {
                        mGetPayResultEmitter?.onComplete()
                        super.dataIsNull(t)
                    }

                    override fun onError(t: Throwable) {
                        mGetPayResultEmitter?.onComplete()
                        super.onError(t)
                    }
                })
        })
            .repeatWhen { return@repeatWhen it.flatMap { return@flatMap Observable.timer(2, TimeUnit.SECONDS) } }
            .subscribe(object : Observer<String> {
                override fun onComplete() {}
                override fun onSubscribe(d: Disposable) {
                    mPollingGetPayResultDisposable = d
                }

                override fun onNext(t: String) {
                    if (t.isNotBlank()) ToastUtil.showToast(t)
                }

                override fun onError(e: Throwable) {
                    d("开始轮询接口:Observable.create:onError:$e")
                }
            })
    }

    private fun removePendingOrder() {
        if (mCollectMoneyBean?.pendingOrder != null) {
            OrderApi.removePendingOrder(this, mCollectMoneyBean?.pendingOrder)
        }
    }

    /*计算实收*/
    private fun calcRealIncome() {
        val totalPrice = try {
            mTotalPriceEt.text.toString().toDouble()
        } catch (e: Exception) {
            0.0
        }
        val discountPercent = try {
            mDiscountPercentEt.text.toString().toInt()
        } catch (e: Exception) {
            100
        }
        mRealIncomeEt.setText(String.format("%.2f", totalPrice * (discountPercent / 100.0)))
    }


    //计算找零
    private fun calcFindZero() {
        val totalPrice = try {
            mTotalPriceEt.text.toString().toDouble()
        } catch (e: Exception) {
            0.0
        }
        val discountPercent = try {
            mDiscountPercentEt.text.toString().toInt()
        } catch (e: Exception) {
            100
        }
        val realIncome = try {
            mRealIncomeEt.text.toString().toDouble()
        } catch (e: Exception) {
            0.0
        }
        val calcRealTotalPrice = UtilsBigDecimal.mul(totalPrice, UtilsBigDecimal.div(discountPercent.toDouble(), 100.0).toDouble()).toDouble()
        var findZero = UtilsBigDecimal.sub(realIncome, calcRealTotalPrice).toDouble()
        mFindZeroTv.text = String.format("%.2f", findZero)
    }

    //更新 支付按钮的组件样式
    private fun updatePayUi(type: Int, avt: AutofitTextView) {
        mCurPayType = type
        mPayBtnListAtv.forEach {
            it.isSelected = false
        }
        avt.isSelected = true
        mPayTypeNameTv.text = avt.text.toString()
//        when (type) {
//            PAY_TYPE_CASH -> {
//                mCashPayAtv.isSelected = true
//                mVipPayAtv.isSelected = false
//                mVipCardPayAtv.isSelected = false
//                mJuHePayAtv.isSelected = false
//                mScanQrPayAtv.isSelected = false
//                mPayTypeNameTv.text = "现金"
//            }
//            PAY_TYPE_WETCH_VIP -> {
//                mCashPayAtv.isSelected = false
//                mVipPayAtv.isSelected = true
//                mVipCardPayAtv.isSelected = false
//                mJuHePayAtv.isSelected = false
//                mScanQrPayAtv.isSelected = false
//                mPayTypeNameTv.text = "会员码"
//            }
//            PAY_TYPE_VIP_CARD -> {
//                mCashPayAtv.isSelected = false
//                mVipPayAtv.isSelected = false
//                mVipCardPayAtv.isSelected = true
//                mJuHePayAtv.isSelected = false
//                mScanQrPayAtv.isSelected = false
//                mPayTypeNameTv.text = "会员卡"
//            }
//            PAY_TYPE_JUHE -> {
//                mCashPayAtv.isSelected = false
//                mVipPayAtv.isSelected = false
//                mVipCardPayAtv.isSelected = false
//                mJuHePayAtv.isSelected = true
//                mScanQrPayAtv.isSelected = false
//                mPayTypeNameTv.text = "聚合码"
//            }
//            PAY_TYPE_SCAN_QR -> {
//                mCashPayAtv.isSelected = false
//                mVipPayAtv.isSelected = false
//                mVipCardPayAtv.isSelected = false
//                mJuHePayAtv.isSelected = false
//                mScanQrPayAtv.isSelected = true
//                mPayTypeNameTv.text = "扫码收款"
//            }
//            else -> {
//                mCashPayAtv.isSelected = false
//                mVipPayAtv.isSelected = false
//                mVipCardPayAtv.isSelected = false
//                mJuHePayAtv.isSelected = false
//                mScanQrPayAtv.isSelected = false
//                mPayTypeNameTv.text = "未知"
//            }
//        }
    }

    override fun isRegisterEventBus(): Boolean = true
    override fun receiveEvent(event: Event<Any>) {
        super.receiveEvent(event)
        when (event.code) {
            EventCode.ORDER_CANCEL -> cancelPollingGetPayResult()
            EventCode.ORDER_PAY_RESULT -> {
                //TODO:会员码和聚合码支付和扫码枪结果回调
                mWaitingPayDialog?.dismiss()
                EventBusUtil.sendEvent(Event(EventCode.COLLECT_MONEY_SUCCESS))
                //如果是挂单的话，恢复原先状态。
                removePendingOrder()
                goBack()
            }
            EventCode.READER_CARD_HEX_STRING -> readCard(event.data as String)
            EventCode.COLLECT_MONEY_POLLING_REQUEST_PAY_RESULT_START -> pollingRequestPayResult(event.data as ServerOrderResult)
            EventCode.COLLECT_MONEY_POLLING_REQUEST_PAY_RESULT_CANCEL -> cancelPollingGetPayResult()
            else -> {}
        }
    }

    private fun readCard(carStr: String) {
        if (mCurPayType == PAY_TYPE_VIP_CARD && orderDB != null && mWaitingPayDialog != null && mWaitingPayDialog!!.isShowing) {
            //存放卡号 carStr
            d("carStr:$carStr")
            var sob = OrderApi.toServerOrderBean(orderDB!!)
            d("sob.card:${sob.card}")
            NormalApi.postPay(
                sortedMapOf(
                    Params.pay_t to sob.pay_t, Params.price to sob.price, Params.data to CommUtils.gson.toJson(sob.data),
                    Params.d_price to orderDB?.giftPrice, Params.gd_price to orderDB?.totalGiftPrice, Params.diff_price to orderDB?.findZero,
                    Params.d_c to String.format("%.2f", (orderDB?.discountPercent ?: 0) / 100.0),
                    Params.od_n to sob.od_n, Params.c_time to sob.c_time, Params.wg to sob.wg, Params.card to carStr
                ), Urls.pay
            )
                .compose(RxUtils.aLifecycle(this))
                .compose(RxUtils.io())
                .subscribe(object : DialogObserver<ServerOrderResult>(this) {
                    override fun onSuccessNext(t: BaseBean<out ServerOrderResult>) {
                        var data = t.data!!
                        //把订单状态改成已支付。
                        orderDB!!.uploadStatus = 1
                        orderDB!!.orderStatus = OrderApi.ORDER_STATUS_PAID
                        //这里应该还需要保存 积分二维码.
                        orderDB!!.integralUrl = data.integral_url
                        //TODO:这里应该还需要存放卡号。
                        App.mDaoSession?.orderDBDao?.update(orderDB)
                        //是否打印？
                        if (isAutoConnectPrint) PrinterAll.printOrder(PrintOrderBean.orderDB2PrintOrderBean(orderDB))
                        mWaitingPayDialog?.dismiss()
                        EventBusUtil.sendEvent(Event(EventCode.COLLECT_MONEY_SUCCESS))
                        //如果是挂单的话，恢复原先状态。
                        removePendingOrder()
                        goBack()
                    }
                })
        } else {
            //检查会员信息
            NormalApi.getVipInfo(sortedMapOf(Params.tp to 3, Params.card_n to carStr), Urls.memberCard)
                .compose(RxUtils.io())
                .compose(RxUtils.aLifecycle(this))
                .subscribe(object : NormalObserver<ServerVipInfo>() {
                    override fun onSuccessNext(t: BaseBean<out ServerVipInfo>) {
                        var data = t.data!!
                        val sb = StringBuilder()
                        sb.appendLine("名称：${data.name.isNotAvailable()}")
                        sb.appendLine("手机：${data.mobile.isNotAvailable()}")
                        sb.appendLine("卡号：${data.card_n.isNotAvailable()}")
                        sb.appendLine("积分：${data.integral.isNotAvailable()}")
                        sb.appendLine("余额：${data.money.isNotAvailable()}")
                        ToastUtil.showToast(sb.toString())
                    }
                })
        }
    }

    override fun onDestroy() {
        mWaitingPayDialog?.dismiss()
        super.onDestroy()
    }
}